package com.qf.springcloud.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证Filter
 */
@Component
public class AuthenticationFilter extends ZuulFilter {

    // 过滤器类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    // 过滤器执行顺序
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER - 1;
    }

    // 是否开启当前过滤器
    @Override
    public boolean shouldFilter() {
        return true;   // 开启
    }

    @Override
    public Object run() throws ZuulException {
    //        要求请求参数中,携带一个token=123,认证通过
        //1. 获取request对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //2. 通过request获取参数token
        String token = request.getParameter("token");

        //3. 判断是否是123,如果不是直接401没有权限
        if(StringUtils.isEmpty(token) || !token.equals("123")){
            // 返回401,请求拦截
            context.setResponseStatusCode(401);
            context.setSendZuulResponse(false);//  拦截请求不继续往下走
        }

        return null;   // return的结果没有任何意义
    }
}
